package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import model.Achat;
import model.Paiement;
import dao.DaoAchat;
import dao.DaoPaiement;

/**
 * Servlet implementation class Commande
 */
public class Commande extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Commande() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		HttpSession session = request.getSession();
		DaoPaiement daopaiement = new DaoPaiement();
		DaoAchat daoachat = new DaoAchat();
		Achat achat = new Achat();
		Paiement paiement = new Paiement();
		
		achat = (Achat)session.getAttribute("achat");
		daoachat.create(achat);
		
		int idachat = daoachat.getLastIdAchat(achat);
		
		if(request.getParameter("numcarte") == null){
			paiement.setIdAchat(idachat);
			paiement.setComptePaypal(request.getParameter("comptepaypal"));
			paiement.setNomDetenteur(request.getParameter("nom") +" "+ request.getParameter("prenom"));
			daopaiement.create(paiement);
			request.getRequestDispatcher("/messages.jsp").forward( request, response );
		}
		else{
			paiement.setIdAchat(idachat);
			paiement.setNomDetenteur(request.getParameter("nomcarte"));
			paiement.setNumeroCarte(request.getParameter("numcarte"));
			paiement.setDateValidite(request.getParameter("datevalidite"));
			paiement.setCryptogramme(request.getParameter("crypto"));
			daopaiement.create(paiement);
			request.getRequestDispatcher("/messages.jsp").forward(request,  response);
		}
		
		session.setAttribute("achat", null);
		session.setAttribute("billet", null);
	}

}
